<template>
    <div class="page-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>交易订单列表</span>
                    <div>
                        <el-button type="primary" @click="openCreateOrderDialog">创建新订单</el-button>
                        <el-button type="warning" @click="fetchFailedOrders">查看失败订单</el-button>
                    </div>
                </div>
            </template>

            <el-form :model="searchParams" inline class="search-form">
                <el-form-item label="订单ID">
                    <el-input v-model="searchParams.orderId" placeholder="请输入订单ID" clearable></el-input>
                </el-form-item>
                <el-form-item label="用户ID">
                    <el-input v-model="searchParams.userId" placeholder="请输入用户ID" clearable></el-input>
                </el-form-item>
                <el-form-item label="订单状态">
                    <el-select v-model="searchParams.status" placeholder="选择状态" clearable>
                        <el-option label="待审批" value="PENDING_APPROVAL"></el-option>
                        <el-option label="已批准" value="APPROVED"></el-option>
                        <el-option label="已结算" value="SETTLED"></el-option>
                        <el-option label="失败" value="FAILED"></el-option>
                        <el-option label="已拒绝" value="REJECTED"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="orders" v-loading="loading" style="width: 100%">
                <el-table-column prop="id" label="订单ID" width="100"></el-table-column>
                <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
                <el-table-column prop="accountId" label="账户ID" width="100"></el-table-column>
                <el-table-column prop="productId" label="组合ID" width="100"></el-table-column>
                <el-table-column prop="type" label="交易类型" width="120">
                    <template #default="scope">
                        <el-tag :type="getTypeTag(scope.row.type)">{{ scope.row.type }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="交易金额" width="120">
                    <template #default="scope">{{ scope.row.amount.toFixed(2) }}</template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                        <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="scope">{{ new Date(scope.row.createTime).toLocaleString() }}</template>
                </el-table-column>
                <el-table-column label="操作" width="280" fixed="right">
                    <template #default="scope">
                        <el-button size="small" @click="viewDetails(scope.row.id)">详情</el-button>
                        <el-button size="small" type="success" @click="approveOrder(scope.row)"
                            :disabled="scope.row.status !== 'PENDING_APPROVAL'">批准</el-button>
                        <el-button size="small" type="danger" @click="rejectOrder(scope.row)"
                            :disabled="scope.row.status !== 'PENDING_APPROVAL'">拒绝</el-button>
                        <el-button size="small" type="info" @click="settleOrder(scope.row)"
                            :disabled="scope.row.status !== 'APPROVED'">交割</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-if="total > 0" class="pagination" :current-page="currentPage" :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useAuthStore } from '@/store/auth';

const router = useRouter();
const authStore = useAuthStore();

const orders = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const searchParams = reactive({
    orderId: '',
    userId: '',
    status: '',
});

// 模拟从 tradeApi 导入函数，实际使用 axios
const tradeApi = {
    getTradeOrders: (params) => axios.get('/api/trade/orders/page', { params }),
    getFailedOrders: () => axios.get('/api/trade/orders/failed'),
    approveTradeOrder: (orderId, approverId) => axios.post(`/api/trade/order/${orderId}/approve`, { approverId }),
    rejectTradeOrder: (orderId, approverId, reason) => axios.post(`/api/trade/order/${orderId}/reject`, { approverId, reason }),
};

const fetchOrders = async () => {
    loading.value = true;
    try {
        const params = {
            page: currentPage.value - 1,
            size: pageSize.value,
            ...searchParams
        };
        const response = await tradeApi.getTradeOrders(params);
        orders.value = response.data.content;
        total.value = response.data.totalElements;
    } catch (error) {
        ElMessage.error('获取订单列表失败: ' + (error.response?.data?.message || error.message));
        orders.value = [];
        total.value = 0;
    } finally {
        loading.value = false;
    }
};

const fetchFailedOrders = async () => {
    loading.value = true;
    try {
        const response = await tradeApi.getFailedOrders();
        orders.value = response.data;
        total.value = response.data.length; // 失败订单列表可能不是分页的
        ElMessage.info('已加载所有失败或部分失败的订单。');
    } catch (error) {
        ElMessage.error('获取失败订单列表失败: ' + (error.response?.data?.message || error.message));
    } finally {
        loading.value = false;
    }
};

const statusMap = {
    PENDING: { text: '待审批', type: 'warning' },
    APPROVED: { text: '已批准', type: '' },
    COMPLETED: { text: '已完成', type: 'success' },
    SETTLED: { text: '已结算', type: 'success' },
    PARTIALLY_SETTLED: { text: '部分结算', type: 'primary' },
    FAILED: { text: '失败', type: 'danger' },
    REJECTED: { text: '已拒绝', type: 'info' },
};

const getStatusText = (status) => statusMap[status]?.text || '未知';
const getStatusTag = (status) => statusMap[status]?.type || 'info';

const typeMap = {
    BUY: { type: 'danger' },
    SELL: { type: 'success' },
    REBALANCE: { type: 'primary' },
};
const getTypeTag = (type) => typeMap[type]?.type || 'info';


const handleSearch = () => {
    currentPage.value = 1;
    fetchOrders();
};

const resetSearch = () => {
    searchParams.orderId = '';
    searchParams.userId = '';
    searchParams.status = '';
    handleSearch();
};

const handleSizeChange = (size) => {
    pageSize.value = size;
    fetchOrders();
};

const handleCurrentChange = (page) => {
    currentPage.value = page;
    fetchOrders();
};

const approveOrder = async (order) => {
    const approverId = authStore.state.user?.id;
    if (!approverId) {
        ElMessage.error('无法获取审批人ID，请重新登录。');
        return;
    }
    try {
        await tradeApi.approveTradeOrder(order.id, approverId);
        ElMessage.success(`订单 ${order.id} 已批准`);
        fetchOrders();
    } catch (error) {
        ElMessage.error('批准失败: ' + (error.response?.data?.message || error.message));
    }
};

const rejectOrder = (order) => {
    const approverId = authStore.state.user?.id;
    if (!approverId) {
        ElMessage.error('无法获取审批人ID，请重新登录。');
        return;
    }
    ElMessageBox.prompt('请输入拒绝原因', '拒绝订单', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValidator: (val) => val ? true : '拒绝原因不能为空',
    }).then(async ({ value }) => {
        try {
            await tradeApi.rejectTradeOrder(order.id, approverId, value);
            ElMessage.info(`订单 ${order.id} 已被拒绝`);
            fetchOrders();
        } catch (error) {
            ElMessage.error('拒绝失败: ' + (error.response?.data?.message || error.message));
        }
    }).catch(() => {
        ElMessage.info('已取消操作');
    });
};

const openCreateOrderDialog = () => {
    router.push({ name: 'CreateTradeOrder' });
};

const viewDetails = (id) => {
    router.push({ name: 'TradeOrderDetail', params: { id } });
};

const settleOrder = (order) => {
    router.push({ name: 'TradeSettlement', params: { id: order.id } });
};
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-form {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>